import 'dart:io';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import '../models/camera_models.dart';
import '../generated/camera_api.g.dart';

/// 权限管理器
///
/// 负责处理相机权限的检查、请求和用户引导
class PermissionManager {
  /// 简单的相机权限检查和处理
  static Future<CameraPermissionResult> handleCameraPermission(
    BuildContext? context, {
    bool showDialog = true,
  }) async {
    try {
      debugPrint('🔐 开始检查相机权限...');

      // 1. 检查当前权限状态
      final status = await Permission.camera.status;
      debugPrint('🔐 相机权限状态: $status');

      // 2. 如果已经授权，直接返回成功
      if (status.isGranted) {
        debugPrint('🔐 相机权限已授权');
        return CameraPermissionResult(
          isGranted: true,
          hasCameraPermission: true,
        );
      }

      // 2.1 如果permission_handler显示denied，但用户说权限是开启的，用原生方法验证
      if (status.isDenied) {
        debugPrint('🔐 permission_handler显示denied，尝试原生验证...');
        final nativeResult = await checkCameraPermissionNative();
        if (nativeResult) {
          debugPrint('🔐 原生验证成功！permission_handler可能有误');
          return CameraPermissionResult(
            isGranted: true,
            hasCameraPermission: true,
          );
        }
      }

      // 3. 如果被永久拒绝，引导用户去设置
      if (status.isPermanentlyDenied) {
        debugPrint('🔐 相机权限被永久拒绝，需要手动设置');

        if (showDialog && context != null) {
          final shouldOpenSettings = await _showPermissionDialog(
            context,
            title: '需要相机权限',
            message: '相机权限被拒绝，请前往系统设置手动开启相机权限。',
            positiveButton: '去设置',
            negativeButton: '取消',
          );

          if (shouldOpenSettings == true) {
            await openAppSettings();
          }
        }

        return CameraPermissionResult(
          isGranted: false,
          hasCameraPermission: false,
          needsManualSettings: true,
        );
      }

      // 4. 如果被拒绝或未确定，请求权限
      if (status.isDenied) {
        debugPrint('🔐 请求相机权限...');
        final requestStatus = await Permission.camera.request();
        debugPrint('🔐 请求结果: $requestStatus');

        if (requestStatus.isGranted) {
          debugPrint('🔐 相机权限请求成功');
          return CameraPermissionResult(
            isGranted: true,
            hasCameraPermission: true,
          );
        } else if (requestStatus.isPermanentlyDenied) {
          debugPrint('🔐 用户选择了永不再问');

          if (showDialog && context != null) {
            final shouldOpenSettings = await _showPermissionDialog(
              context,
              title: '权限被拒绝',
              message: '相机权限被拒绝，请前往系统设置手动开启相机权限。',
              positiveButton: '去设置',
              negativeButton: '取消',
            );

            if (shouldOpenSettings == true) {
              await openAppSettings();
            }
          }

          return CameraPermissionResult(
            isGranted: false,
            hasCameraPermission: false,
            needsManualSettings: true,
          );
        } else {
          debugPrint('🔐 用户拒绝了权限请求');
          return CameraPermissionResult(
            isGranted: false,
            hasCameraPermission: false,
            userDenied: true,
          );
        }
      }

      // 5. 其他状态（限制等）
      debugPrint('🔐 权限状态异常: $status');
      return CameraPermissionResult(
        isGranted: false,
        hasCameraPermission: false,
        hasError: true,
      );
    } catch (e) {
      debugPrint('🔐 权限检查出错: $e');
      return CameraPermissionResult(
        isGranted: false,
        hasCameraPermission: false,
        hasError: true,
        errorMessage: e.toString(),
      );
    }
  }

  /// 显示权限对话框
  static Future<bool?> _showPermissionDialog(
    BuildContext context, {
    required String title,
    required String message,
    required String positiveButton,
    String? negativeButton,
  }) async {
    return showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(title),
          content: Text(message),
          actions: [
            if (negativeButton != null)
              TextButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: Text(negativeButton),
              ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(true),
              child: Text(positiveButton),
            ),
          ],
        );
      },
    );
  }

  /// 快速检查相机权限状态（不请求，不显示对话框）
  static Future<bool> checkCameraPermissionQuick() async {
    try {
      final status = await Permission.camera.status;
      return status.isGranted;
    } catch (e) {
      debugPrint('🔐 快速权限检查出错: $e');
      return false;
    }
  }

  /// 使用原生方法检查相机权限（备用方案）
  static Future<bool> checkCameraPermissionNative() async {
    try {
      // 使用原生API检查权限
      final result = await MultiCameraHostApi().checkCameraPermissionNative();
      debugPrint('🔐 原生权限检查结果: $result');
      return result;
    } catch (e) {
      debugPrint('🔐 原生权限检查出错: $e');
      return false;
    }
  }
}

/// 相机权限处理结果
class CameraPermissionResult {
  /// 是否获得了使用相机所需的全部权限
  final bool isGranted;

  /// 是否有相机权限
  final bool hasCameraPermission;

  /// 是否有麦克风权限（如果需要的话）
  final bool? hasMicrophonePermission;

  /// 是否需要用户手动到设置中开启
  final bool needsManualSettings;

  /// 用户是否主动拒绝了权限
  final bool userDenied;

  /// 是否有错误
  final bool hasError;

  /// 错误信息
  final String? errorMessage;

  const CameraPermissionResult({
    required this.isGranted,
    required this.hasCameraPermission,
    this.hasMicrophonePermission,
    this.needsManualSettings = false,
    this.userDenied = false,
    this.hasError = false,
    this.errorMessage,
  });

  @override
  String toString() {
    return 'CameraPermissionResult('
        'isGranted: $isGranted, '
        'hasCameraPermission: $hasCameraPermission, '
        'hasMicrophonePermission: $hasMicrophonePermission, '
        'needsManualSettings: $needsManualSettings, '
        'userDenied: $userDenied, '
        'hasError: $hasError, '
        'errorMessage: $errorMessage)';
  }
}
